var createError = require('http-errors');//处理http错误的一个模块
var express = require('express');//express核心库
var path = require('path');//路径模块
var cookieParser = require('cookie-parser');//用于处理cookie
var logger = require('morgan');//日志插件

//这两个是路由页面
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
let videoRouter = require('./routes/video');
//搭建了一个服务
var app = express();

// view engine setup
// 视图引擎设置
app.set('views', path.resolve('views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//静态资源:视频 音频 图片 各种文档 这些都是属于静态资源
//练习:托管静态资源 让其他人能够访问 windows系统一定要关闭防火墙
//windows输入 ipcofig ipv4地址就是局域网地址
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.resolve("assets")))

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Credentials", "true")//允许携带凭证,比如cookie
    res.header("Access-Control-Allow-Origin", "*")//后端处理跨域的核心代码
    res.header("Access-Control-Allow-Headers", "authorization,Content-Type");//允许的请求头
    res.header("Access-Control-Allow-Methods", "POST,GET,DELETE,OPTIONS");//允许的请求方式
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");//内容类型 MIME类型都可以在这定义
    next();
});
//配置路由
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/video', videoRouter);
app.use('/jsonp', function (req, res, next) {
    //可以获取query参数
    console.log(req.query)
    //获取前端传递过来的回调函数的key
    let { cb } = req.query;

    let result = JSON.stringify({ state: true, msg: "jsonp请求成功" }
    )


    res.send(`${cb}(${result})`)
    next() //释放控制权给下一个中间件
})

module.exports = app;
